﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Omu.Awesome.Mvc
{
    internal class WhiteSpaceStream : Stream
    {
        private readonly Stream m_sink;
        private static readonly Regex m_regex = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");

        public WhiteSpaceStream(Stream sink)
        {
            m_sink = sink;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override void Flush()
        {
            m_sink.Flush();
        }

        public override long Length
        {
            get { return 0; }
        }

        public override long Position { get; set; }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return m_sink.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return m_sink.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            m_sink.SetLength(value);
        }

        public override void Close()
        {
            m_sink.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            byte[] data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);
            string text = Encoding.Default.GetString(buffer);

            text = m_regex.Replace(text, string.Empty);

            byte[] outdata = Encoding.Default.GetBytes(text);
            m_sink.Write(outdata, 0, outdata.GetLength(0));
        }
    }
}